<template>
  <div ref="imageWrapper">
    <a-card title="查询条件" class="search">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="5" :sm="6">
              <a-form-model-item label="机构名称" prop="orgName">
                <a-input v-model="queryParam.orgName" readOnly placeholder="请选择" @click.native="openOrganModel" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="审计期间" prop="arrayTime">
                <a-range-picker
                  v-model="queryParam.arrayTime"
                  format="yyyy-MM-DD"
                  value-format="yyyy-MM-DD"
                  @change="handleDatechange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="审计时间" prop="arrayTime">
                <a-date-picker
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择结束时间"
                  v-model="queryParam.finishTime"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="6">
              <a-button
                type="primary"
                style=" background-color: #000e89; border: 1px solid #000e89"
                @click="ShowItemOfIndicator"
                >指标筛选</a-button
              >
              <a-button type="primary" icon="download" style="margin-left: 10px;" @click="download">导出</a-button>
            </a-col>
            <a-col :md="5" :sm="6">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button type="primary" @click="onSearch" icon="search" class="yellow_search_btn">查询</a-button>
                <a-button @click="searchReset" icon="reload" class="clear_btn">清除条件</a-button>
                <a-button
                  type="danger"
                  :loading="loading"
                  icon="arrow-right"
                  style="margin-left: 18px"
                  @click="handleToYD1"
                  >转疑点</a-button
                >
                <a-button v-if="isBackButton" type="primary" style="margin-left: 8px" @click="backUppage">
                  返回
                </a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card style="margin-top: 20px" class="img_css">
      <div class="Exceed_funds_map">
        <div class="title">
          <span>主要材料成本归集模型</span>
        </div>
        <a-spin :spinning="loadingicon">
          <div class="content-zy">
            <div class="top">
              <div class="circle-line">
                <div
                  :class="{ item: true, itemWraning: item.warn == 1 }"
                  v-for="(item, index) in itemlist"
                  :key="index"
                  @click="handlerClick(item, index)"
                >
                  <img v-if="item.warn == 1" class="icon" :src="item.redicon" alt="" />
                  <img v-else class="icon" :src="item.icon" alt="" />
                  <span class="text">{{ item.name }}</span>
                  <span class="num">{{ item.num || item.frndbwzhj }}</span>
                  <div class="line-data" v-if="item.deviation">
                    {{ item.deviation }}
                  </div>
                </div>
              </div>
            </div>
            <div class="bottom">
              <div :class="{ item: true, itemWraning: item.warn == 1 }" v-for="(item, index) in itemlist2" :key="index">
                <span>{{ item.name }} </span><span>{{ item.zclhsjce || item.yhclywzzmcb }}</span>
              </div>
            </div>
          </div>
        </a-spin>
      </div>
    </a-card>
    <a-card style="margin-top: 20px">
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :row-selection="rowSelection"
        @change="handleTableChange"
        class="antableClass"
      >
      </a-table>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        bordered
        :columns="columns2"
        :dataSource="dataSource2"
        :pagination="false"
        class="antableClass"
        style="margin-top:20px"
      >
      </a-table>
    </a-card>
    <AuditDepart ref="AuditDepart" @selectedRow="updateQueryParam" />
    <ItemsOfIndicator ref="itemsofindicator" @save="editIndicator" />
    <CheckTable ref="CheckTable" @RelaodData="RelaodData" />
    <YDModel ref="YDModel" :routerData="$route.path" />
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { base64toImg } from '@/mixins/base64toImg'
import { getAction, putAction, postAction, downFile } from '@/api/manage'
import AuditDepart from '@/views/sj/sjmxgl/cwzb/components/AuditDepart'
import ItemsOfIndicator from './ItemsOfIndicator.vue'
import CheckTable from '@/views/sj/sjmxgl/zyclcbgjmx/CheckTable'
import columns from './columns.js'
import YDModel from '@/views/sj/components/YDModel'
export default {
  mixins: [JeecgListMixin, base64toImg],
  components: { AuditDepart, ItemsOfIndicator, CheckTable, YDModel },
  computed: {
    // 行选择
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = [...selectedRowKeys]
          this.selectedRows = [...selectedRows]
        }
      }
    }
  },
  data() {
    return {
      queryParam: {
        orgName: '中铁一局长春建筑工程公司桓仁至集安高速公路第03工区项目部',
        startTime: '2022-01-01',
        endTime: '2022-12-31'
      },
      superParam: {
        id: '1',
        modelId: '1',
        extraFlag: true
      },
      url: {
        // 查询模型转疑点信息(多选)
        TurnSuspects: '/sjmx/queryModelMsgMulti',
        // 查询模型筛选项信息
        indicator: '/sjmx/sjModelFieldConfig/queryModelField',
        // 设置模型筛选项信息
        editIndicator: '/sjmx/sjModelFieldConfig/edit',
        zbje: '/sjmx2Test/queryZbje',
        list: '/sjmx2Test/queryZyclcbData',
        tipsList: '/sjmx2Test/queryNote',
        export: '/sjmx2Test/expertZyclcbData'
      },
      rules: {
        orgName: [{ required: true, message: '请选择审计单位' }]
      },
      isBackButton: false,
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      columns: columns(this),
      loadingicon: false,
      itemlist: [
        {
          icon: require('@/assets/zy-icon.png'),
          redicon: require('@/assets/zy-icon-red.png')
        },
        {
          icon: require('@/assets/zy-icon.png'),
          redicon: require('@/assets/zy-icon-red.png')
        },
        {
          icon: require('@/assets/zy-icon-b.png'),
          redicon: require('@/assets/zy-red-icon.png')
        },
        {
          icon: require('@/assets/zy-icon.png'),
          redicon: require('@/assets/zy-icon-red.png')
        }
      ],
      itemlist2: [],
      itemListTagorder: [
        { tag: 'yxhclje', type: 'itemlist', index: 0 },
        { tag: 'sjfscbje', type: 'itemlist', index: 1 },
        { tag: 'zmcbze', type: 'itemlist', index: 2 },
        { tag: 'frndbwzhj', type: 'itemlist', index: 3 },
        { tag: 'zclhsjce', type: 'itemlist2', index: 0 },
        { tag: 'yhclywzzmcb', type: 'itemlist2', index: 1 }
      ],
      disableMixinCreated: true,
      columns2: [
        {
          title: '序号',
          dataIndex: 'rowIndex',
          width: 180,
          align: 'center',
          customRender: function(t, r, index) {
            return `提示 ${parseInt(index) + 1}`
          }
        },
        {
          title: '异常信息',
          dataIndex: 'note',
          align: 'center'
        }
      ],
      dataSource2: []
    }
  },
  mounted() {},
  //   watch: {
  //     $route: {
  //       handler: function(to) {
  //         if (Object.keys(to.query).length) {
  //           debugger
  //           this.disableMixinCreated = true
  //           let { orgName, selectedKeys, orgId, unitId, startTime, endTime } = to.query
  //           this.selectedRowKeys = selectedKeys.split(',')
  //           this.queryParam = Object.assign(this.queryParam, {
  //             orgName,
  //             orgId,
  //             unitId,
  //             startTime,
  //             endTime,
  //             arrayTime: [startTime, endTime]
  //           })
  //           this.$nextTick(() => {
  //             this.onSearch()
  //           })
  //         }
  //       },
  //       immediate: true
  //     }
  //   },
  methods: {
    searchReset() {
      this.queryParam = this.$options.data().queryParam
      this.itemlist = this.$options.data().itemlist
      this.itemlist2 = this.$options.data().itemlist2
      this.dataSource2 = []
      this.dataSource = []
    },
    onSearch() {
      this.$refs.ruleForm.validate(value => {
        if (value) {
          Promise.all([this.loadData(1), this.getData()]).then(() => {
            this.getTipsList()
          })
        } else {
          this.$message.warning('请选择审计单位和审计时间')
        }
      })
    },
    openOrganModel() {
      this.$refs.AuditDepart.show()
    },
    updateQueryParam(checkRow) {
      console.log(checkRow)
      this.queryParam.orgName = checkRow.departName
      this.queryParam.orgId = checkRow.id
      this.queryParam.unitId = checkRow.id
    },
    handleToYD1(record) {
      if (this.dataSource.length) {
        this.loading = true
        const { startTime = '', endTime = '' } = this.queryParam
        let ydnr = undefined
        let gzzd = undefined
        let time = `【${startTime}～${endTime}】【设备物资-供应商管理】`
        console.log('this.activeKey------>', this.activeKey)
        let selectedRowKeys = this.selectedRows.map(item => item.id)

        let param = Object.assign({}, this.queryParam, { selectedKeys: selectedRowKeys.join(',') })
        let ydList = this.getselectRowJosn(this.selectedRows)
        postAction(this.url.TurnSuspects, Object.assign({}, this.queryParam, this.superParam, { ydList: ydList })).then(
          res => {
            if (res.success) {
              if (res.result.length) {
                ydnr = res.result[0].ydms ? res.result[0].ydms : ydnr
                gzzd = res.result[0].gzzd ? res.result[0].gzzd : gzzd
              }
              this.addYdMulti(param, ydnr, time, gzzd)
            }
            if (res.code === 510) {
              this.$message.warning(res.message)
            }
            this.loading = false
          }
        )
      } else {
        this.$message.error('空数据不能新建疑点')
      }
    },
    getselectRowJosn(selectedRows) {
      selectedRows.map(item => {
        item.zb = item.target
      })
      return JSON.stringify(selectedRows)
    },
    // 展示模型筛选项信息
    ShowItemOfIndicator() {
      this.GetItemOfIndicator()
    },
    // 查询模型筛选项信息
    GetItemOfIndicator() {
      getAction(this.url.indicator, Object.assign({}, this.queryParam, this.superParam)).then(res => {
        if (res.success) {
          let projectItem = Object.assign({}, JSON.parse(res.result.projectJson))
          this.$refs.itemsofindicator.edit(projectItem)
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    // 保存已经修改的projectJson(子组件返回json串)
    editIndicator(projectJson) {
      putAction(this.url.editIndicator, Object.assign({}, this.queryParam, this.superParam, { projectJson })).then(
        res => {
          console.log(res)
        }
      )
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    },
    // 导出表格
    download() {
      if (this.dataSource.length != 0) {
        this.downloadFile(this.url.export, '主要材料成本归集模型', this.queryParam).then(res => {
          if (res.success) {
          }
        })
      } else {
        this.$message.warning('请先查询')
      }
    },
    handleDownloadFile(fileUrl) {
      this.$message.success('正在下载，请稍等！')
      let url = `${window._CONFIG['domianURL']}/sys/common/download/${fileUrl}`
      window.open(url, '_blank')
    },
    async getData() {
      try {
        this.loadingicon = true
        let res = await getAction(this.url.zbje, this.queryParam)
        if (res.success) {
          this.itemListTagorder.map(item => {
            this[item.type][item.index] = { ...this[item.type][item.index], ...res.result[item.tag] }
          })
        } else {
          throw new Error(res.message)
        }
        this.loadingicon = false
      } catch (error) {
        this.$message.error(error)
        console.log(error)
      }
      return Promise.resolve(1)
    },
    handlerClick(record, index) {
      console.log(record, 'recordrecordrecordrecordrecordrecordrecordrecord')
      console.log(index)
      this.$refs.CheckTable.check(index, this.queryParam, record)
    },
    RelaodData() {
      this.getData()
    },
    async getTipsList() {
      try {
        let res = await getAction(this.url.tipsList, { xmbmc: this.queryParam.orgName })
        if (res.success) {
          this.dataSource2 = res.result
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        this.$message.error(error)
      }
    },
    downloadFile(url, fileName, parameter) {
      return downFile(url, parameter).then(data => {
        if (!data || data.size === 0) {
          Vue.prototype['$message'].warning('文件下载失败')
          return
        }
        debugger
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName)
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';
@leftjl: 50px;
.img_css /deep/ .ant-card-body {
  padding: 15px 15px 0 15px;
}
.Exceed_funds_map {
  width: 100%;
  position: relative;
  .title {
    // width: 350px;
    height: 50px;
    text-align: center;
    margin: 0 auto;
    span {
      cursor: default;
      font-size: 22px;
      color: white;
      padding: 10px 35px 15px;
      border-bottom-left-radius: 30px;
      border-bottom-right-radius: 30px;
      background-color: rgb(1, 69, 142);
    }
  }

  .content-zy {
    margin-top: 80px;
    .top {
      width: 1556px;
      position: relative;
      .circle-line {
        min-width: 1165px;
        margin-left: @leftjl;
        width: 78%;
        height: 65px;
        background: url('~@/assets/zy-bcak.png') no-repeat 100% 100%;
        background-size: 100% 100%;
        .item {
          position: absolute;
          width: 130px;
          height: 131px;
          background-image: url('~@/assets/bule-s.png');
          background-repeat: no-repeat;
          background-size: 100% 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          cursor: pointer;
          .line-data {
            position: absolute;
            width: 213px;
            top: 30px;
            left: 145px;
            text-align: center;
            color: black;
            font-weight: 600;
            cursor: default;
            pointer-events: auto;
          }
          .num {
            color: #f88102;
            font-weight: 600;
            font-size: 16px;
            line-height: 20px;
          }
          .text {
            color: black;
            font-weight: 600;
          }
        }
        .itemWraning {
          width: 195px;
          height: 195px;
          background-image: url('~@/assets/waring.png');
          background-repeat: no-repeat;
          background-size: 100% 100%;
          .num {
            color: #ec3a36;
            font-weight: 600;
          }
          .text {
            color: #ec3a36;
            font-weight: 600;
          }
          .line-data {
            top: 70px;
            color: #ec3a36;
          }
        }
        .item:nth-of-type(1) {
          top: -80%;
          left: calc(170px + @leftjl);
        }
        .item:nth-of-type(2) {
          top: -80%;
          left: calc(546px + @leftjl);
        }
        .item:nth-of-type(3) {
          top: -80%;
          left: calc(920px + @leftjl);
        }
        .item:nth-of-type(4) {
          top: -80%;
          left: calc(1325px + @leftjl);
        }
        .itemWraning:nth-of-type(1) {
          top: -135%;
          left: calc(139px + @leftjl);
        }
        .itemWraning:nth-of-type(2) {
          top: -135%;
          left: calc(518px + @leftjl);
        }
        .itemWraning:nth-of-type(3) {
          top: -135%;
          left: calc(890px + @leftjl);
        }
      }
    }
    .bottom {
      width: 78%;
      margin-top: 50px;
      margin-bottom: 30px;
      margin-left: @leftjl;
      display: flex;
      justify-content: space-around;
      align-items: center;
      .item {
        width: 500px;
        border: 1px solid #00458e;
        padding: 5px 10px;
        box-shadow: 0px 0px 5px #00458e;
        border-radius: 3px;
        color: black;
        display: flex;
        justify-content: space-between;
        align-items: center;

        & > span:nth-of-type(2) {
          font-weight: 600;
          font-size: 16px;
          line-height: 20px;
        }
      }
      .itemWraning {
        border: 1px solid #ec3a36;
        box-shadow: 0px 0px 5px #ec3a36;
        color: #ec3a36;
      }
    }
  }
}
.tipstable {
  width: 100%;
  & > tr > td {
    padding: 12px 8px;
  }
  & > tr > td:nth-of-type(1) {
    width: 16%;
  }
}
</style>
